// pages/goods_detail/index.js
import {getGoodsdetail} from '../../request/goods'
import {showToast} from '../../utils/asyncWx'
Page({
  data: {
    goodsDetail: {},
    isCollect: false //是否收藏
  },

  goodsInfo: {},

  onLoad: function (options) {
    this.getGoodsdetail(options)
  },

  async getGoodsdetail(options) {
    const goodsDetail = await getGoodsdetail(options)
    this.goodsInfo = goodsDetail
    let collect = wx.getStorageSync("collect") || [];
    let isCollect = collect.some(v => v.goods_id === this.goodsInfo.goods_id);
    this.setData({
      goodsDetail: {
        goods_name: goodsDetail.goods_name,
        goods_price: goodsDetail.goods_price,
        goods_introduce: goodsDetail.goods_introduce.replace(/\.webp/g,'.jpg'),
        pics: goodsDetail.pics
      },
      isCollect
    })
  },

  //点击放大图片
  handlePreviewImage(e) {
    const urls = this.goodsInfo.pics.map(value=> value.pics_mid)
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      current,
      urls
    })
  },

  //加入购物车
  handleCartAdd () {
    let cart = wx.getStorageSync('cart') || []
    let index = cart.findIndex(value=> value.goods_id===this.goodsInfo.goods_id)
    if (index===-1) {
      this.goodsInfo.num = 1
      this.goodsInfo.checked = true
      cart.push(this.goodsInfo)
    } else {
      cart[index].num ++
    }
    wx.setStorageSync('cart',cart)
    wx.showToast({
      title: '加入成功',
      mask: true
    })
  },

  /* 收藏 */
  handleCollected() {
    let isCollect = false
    let collect = wx.getStorageSync('collect') || [];
    //判断商品是否被收藏
    let index = collect.findIndex(v => v.goods_id === this.goodsInfo.goods_id);
    if (index!==-1) {
      //商品被收藏，取消收藏
      collect.splice(index, 1);
      isCollect = false;
      showToast({title: '取消成功'})
    } else {
      collect.push(this.goodsInfo);
      isCollect = true;
      showToast({title: '收藏成功'})
    }
    wx.setStorageSync('collect', collect)
    this.setData({
      isCollect
    })
  }
})